package petstore.web.servlet.cart;

import petstore.persistence.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;



@WebServlet("/cartEdit")
public class CartEditServlet extends HttpServlet
{
    public enum typeEnum//定义枚举
    {
        REMOVE(- 1), SUB(0), INC(1);

        private int value = 0;

        private typeEnum(int value) //必须是private的，否则编译错误
        {
            this.value = value;
        }

        public static typeEnum valueOf(int value)
        {    //手写的从int到enum的转换函数
            switch (value)
            {
                case -1:
                    return REMOVE;
                case 0:
                    return SUB;
                case 1:
                    return INC;
                default:
                    return null;
            }
        }

        public int value()
        {
            return this.value;
        }
    };


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String  itemId = req.getParameter("itemId");
        int type = Integer.parseInt(req.getParameter("type"));
        HttpSession session = req.getSession();
        CartDaoImpl cartDao = new CartDaoImpl((int)session.getAttribute("uid"));
        int quantity;
        if(type == typeEnum.INC.value)
        {
            quantity = cartDao.addItem(itemId,1);
        }
        else if(type == typeEnum.SUB.value)
        {
            quantity = cartDao.subItem(itemId);
        }
        else if(type == typeEnum.REMOVE.value)
        {
            quantity = cartDao.removeItem(itemId);
        }
        else
        {
            quantity = -1;
            System.out.println(session.getAttribute("uid") + ":传递了错误的参数");
        }
        int temp = quantity;
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(temp);
    }
}